package com.caval.service;

import com.caval.bean.User;
import com.caval.dao.UserMapper;
import com.caval.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public Map<String, Object> login(String username, String password, HttpSession session) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(username);
        User login = userMapper.login(user);

        Map<String,Object> map = new HashMap<String,Object>();
        if (login != null){
            map.put("token", TokenUtil.token(username,password));
            map.put("msg","success");
            map.put("status",200);
            map.put("user_id",login.getUser_id());
            session.setAttribute("username",login.getUsername());
            session.setAttribute("user_id",login.getUser_id());
        }
        else{
            map.put("msg","failed");
            map.put("status",500);
        }
        return map;
    }

    @Override
    public String regist(String username, String password, String tel, String email) {
        if (this.userExist(username,email)){
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setTel(tel);
            user.setEmail(email);
            userMapper.regist(user);
            return "success";
        }
        return "failed";
    }

    @Override
    public Map<String,Object> getUserById(HttpSession session) {
        if (session.getAttribute("user_id")!=null){
            int user_id = (int) session.getAttribute("user_id");
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("user",userMapper.getUserById(user_id));
            map.put("quantity",userMapper.getQuantity(user_id));
            return map;
        }
        return null;
    }

    @Override
    public boolean userExist(String username,String email) {
        return (userMapper.userExist(username)==0 || userMapper.userExist(email)==0);
    }

}
